import type { FormInstance } from 'element-plus'
import type { aliMapAddressTypes, InfoValuesType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { uniqWith } from 'lodash'
import { ElRow, ElCol, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElLink } from 'element-plus'
import AliIcon from '~/components/AliIocn'
import MapView from '../../components/MapView'
import useVuexGetters from '~/hooks/useVuexGetters'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'MapLocation',
  props: ['detail'],
  setup(props, { expose }) {
    const mapViewRef = ref()
    const ruleFormRef = ref<FormInstance>()
    const selectAddressRef = ref<string>()
    const selectAddressSearchRef = ref<string>()
    const selectAddressOptionsRef = ref<aliMapAddressTypes[]>([])
    const markerPosition = ref<{ lat: number; lng: number }>()
    const formValues = reactive<InfoValuesType>(
      props?.detail
        ? {
            id: props.detail?.id,
            lon: props.detail?.lon,
            lat: props.detail?.lat
          }
        : {}
    )
    const userState = useVuexGetters('user', ['userAddressInfo'])

    // 切换地址选择回调
    const handleChangeAddressSelect = (value: string) => {
      formValues.lon = value?.split(',')[1]!
      formValues.lat = value?.split(',')[0]!
      // 更新地图标记点位置
      markerPosition.value = value?.includes(',')
        ? {
            lng: parseFloat(value?.split(',')[1]!),
            lat: parseFloat(value?.split(',')[0]!)
          }
        : undefined
      if (!mapViewRef.value.mapState.currentMarker) {
        const timer = setTimeout(() => {
          mapViewRef.value.setMarkersByPropsMarkers()
          clearTimeout(timer)
        }, 0)
      }
    }

    // 地图点更换位置后的回调
    const handleSetAddressInfo = (address: string, lngLat: [string, string]) => {
      formValues.lat = lngLat?.[0]
      formValues.lon = lngLat?.[1]
    }

    // 地址选择下拉框输入停止后回调
    const handleFilterAddressSearch = (value: string) => {
      selectAddressSearchRef.value = handleTrim(value)
      handleSearchAddressSelectList()
    }

    // 点击地图左上角查询按钮的时候回调 | 在
    const handleSearchAddressSelectList = (e?: Event) => {
      if (e) e.stopPropagation()
      const placeSearch = new mapViewRef.value.aMapRef.PlaceSearch({
        city: userState.userAddressInfo.value.city,
        citylimit: false
      }) // 构造地点查询类
      placeSearch.search(
        selectAddressSearchRef.value,
        (status: string, result: Record<string, any>) => {
          selectAddressOptionsRef.value =
            status === 'complete' && result.info === 'OK'
              ? uniqWith(
                  result.poiList.pois,
                  (item: { name: string }, nextItem: { name: string }) =>
                    item.name === nextItem.name
                )
              : []
        }
      )
    }

    onMounted(() => {
      if (props.detail?.lat)
        markerPosition.value = {
          lng: props.detail?.lon,
          lat: props.detail?.lat
        }
    })

    expose({ ruleFormRef, formValues })

    return () => (
      <>
        <MapView
          id={styles['map-location-amap']}
          ref={mapViewRef}
          clickon
          marker={markerPosition.value}
          onSetAddressInfo={handleSetAddressInfo}
        />
        <ElFormItem class={styles['map-location-select-address']}>
          <ElSelect
            v-model={selectAddressRef.value}
            filterable
            suffixIcon={<AliIcon type="icon-sousuo" />}
            remote
            defaultFirstOption
            clearable
            placeholder="请输入地址"
            remoteMethod={handleFilterAddressSearch}
            onChange={handleChangeAddressSelect}
          >
            {selectAddressOptionsRef.value?.map((item) => (
              <ElOption
                class={styles['map-location-option-address']}
                key={item?.id}
                label={item?.name}
                value={`${item?.location?.lat},${item?.location?.lng}`}
              >
                <ElLink underline={false} type="info">
                  <AliIcon type="icon-ditudingwei" />
                </ElLink>
                <section class="option-text">
                  <b>{item?.name}</b>
                  <p>{item?.address}</p>
                </section>
              </ElOption>
            ))}
          </ElSelect>
        </ElFormItem>
        <ElForm ref={ruleFormRef} model={formValues} labelWidth={100} labelPosition="right">
          <ElRow gutter={GUTTER}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem prop="lon" label="经度">
                <ElInput v-model={formValues.lat} {...{ maxlength: 50 }} />
              </ElFormItem>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <ElFormItem prop="lat" label="纬度">
                <ElInput v-model={formValues.lon} {...{ maxlength: 50 }} />
              </ElFormItem>
            </ElCol>
          </ElRow>
        </ElForm>
      </>
    )
  }
})
